package com.health.platform.provider.homepage.service;

import com.health.platform.common.core.entity.BaseQueryEntity;
import com.health.platform.common.restful.AppResponse;
import com.health.platform.common.sys.organization.entity.OrganizationEntity;
import com.health.platform.common.sys.organization.service.OrganizationService;
import com.health.platform.common.utils.ThreadLocalUtil;
import com.health.platform.provider.homepage.dao.HomePageDao;
import com.health.platform.provider.homepage.entity.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>首页Service</p>
 * <p>创建日期：2021-02-24</p>
 *
 * @author zhou-qf
 */
@Service
public class HomePageService {

    @Resource
    private HomePageDao homePageDao;

    @Autowired
    private OrganizationService organizationService;

    /**
     * 获取中间部分汇总信息
     * @param baseQueryEntity 参数
     * @return 结果
     */
    public AppResponse getSummaryInfo(BaseQueryEntity baseQueryEntity){
        HomeSummaryEntity homeSummaryEntity = new HomeSummaryEntity();
        // 获取门急诊、互联网人次
        HomeSummaryEntity clinicEmeIntNum = homePageDao.getClinicEmeIntNum(baseQueryEntity);
        if(clinicEmeIntNum != null){
            // 获取门急诊人次
            homeSummaryEntity.setClinicEmeNum(clinicEmeIntNum.getClinicEmeNum());
            // 获取互联网就诊人次
            homeSummaryEntity.setInternetNum(clinicEmeIntNum.getInternetNum());
        } else {
            // 获取门急诊人次
            homeSummaryEntity.setClinicEmeNum(0);
            // 获取互联网就诊人次
            homeSummaryEntity.setInternetNum(0);
        }

        // 获取出生人次
        HomeSummaryEntity bornEntity = homePageDao.getBornNum(baseQueryEntity);
        if(bornEntity != null){
            homeSummaryEntity.setBornBoyNum(bornEntity.getBornBoyNum());
            homeSummaryEntity.setBornGirlNum(bornEntity.getBornGirlNum());
        } else {
            homeSummaryEntity.setBornBoyNum(0);
            homeSummaryEntity.setBornGirlNum(0);
        }
        // 获取出院人次
        HomeSummaryEntity leaveNum = homePageDao.getLeaveHospitalNum(baseQueryEntity);
        if(leaveNum != null){
            homeSummaryEntity.setLeaveHospitalNum(leaveNum.getLeaveHospitalNum());
        } else {
            homeSummaryEntity.setLeaveHospitalNum(0);
        }
        // 获取疫苗接种人次
        HomeSummaryEntity inoculationNum = homePageDao.getInoculationNum(baseQueryEntity);
        if(inoculationNum != null){
            homeSummaryEntity.setInoculationNum(inoculationNum.getInoculationNum());
        } else {
            homeSummaryEntity.setInoculationNum(0);
        }
        // 获取献血人次
        baseQueryEntity.replaceKey("t.GBCODE", "t.BD_GBNAME");
        baseQueryEntity.replaceKey("t.bus_date", "t.BD_DATE");
        baseQueryEntity.setStandbyStr(baseQueryEntity.getConditionStr().replaceAll("t.GBCODE", "t.BD_GBNAME"));
        HomeSummaryEntity donationNum = homePageDao.getDonationNum(baseQueryEntity);
        if(donationNum != null){
            homeSummaryEntity.setDonationNum(donationNum.getDonationNum());
        } else {
            homeSummaryEntity.setDonationNum(0);
        }
        return AppResponse.success("查询成功", homeSummaryEntity);
    }

    /**
     * 获取人群状况
     * @param baseQueryEntity 参数
     * @return 结果
     */
    public AppResponse getCrowdStatus(BaseQueryEntity baseQueryEntity){
        CrowdStatusEntity crowdStatusEntity = new CrowdStatusEntity();
        // 获取人均预期寿命
        CrowdStatusEntity averAge = homePageDao.getAverageLife(baseQueryEntity);
        if(averAge != null){
            crowdStatusEntity.setAverageLife(averAge.getAverageLife());
        } else {
            crowdStatusEntity.setAverageLife(0.0F);
        }

        // 获取人口出生率
        CrowdStatusEntity birthRate = homePageDao.getBirthRate(baseQueryEntity);
        if(birthRate != null){
            crowdStatusEntity.setBirthRate(birthRate.getBirthRate());
        } else {
            crowdStatusEntity.setBirthRate(0.0F);
        }
        CrowdStatusEntity naturalRate = homePageDao.getNaturalRate(baseQueryEntity);
        // 获取人口自然增长率
        if(naturalRate != null){
            crowdStatusEntity.setNaturalRate(naturalRate.getNaturalRate());
        } else {
            crowdStatusEntity.setNaturalRate(0.0F);
        }
        // 如果当前登录是省级用户，那么就查询当前省下各个市的出生率和人口自然增长率 柱状图
        int aType = ThreadLocalUtil.get().getBody().getAreainfo().getAtype();
        // 省级用户
        if(aType == 2){
            List<LocalInfoEntity> resList = new ArrayList<>();
            // 获取当前省下所有市的编号
            OrganizationEntity organizationEntity = new OrganizationEntity();
            organizationEntity.setCurrentQuery(0);
            organizationEntity.setSgbCode(ThreadLocalUtil.get().getBody().getAreainfo().getCode());
            List<OrganizationEntity> list = (List<OrganizationEntity>) organizationService.getOrganization(organizationEntity).getData();
            for(OrganizationEntity organizationEntity1 : list){
                // 重新拼接区划查询条件
                String str = setStr(baseQueryEntity.getConditionStr());
                str += " and t.GBCODE like '"+organizationEntity1.getSgbCode() + "%' ";
                baseQueryEntity.setParamBuilder(new StringBuilder(str));
                // 查询当前市区的出生率
                CrowdStatusEntity localBirthRate = homePageDao.getBirthRate(baseQueryEntity);
                LocalInfoEntity localInfoEntity = new LocalInfoEntity();
                if(localBirthRate != null){
                    localInfoEntity.setBirthRate(birthRate.getBirthRate());
                } else {
                    localInfoEntity.setBirthRate(0.0F);
                }
                // 查询当前市区的人口自然增长率
                CrowdStatusEntity localNaturalRate = homePageDao.getNaturalRate(baseQueryEntity);
                if(localNaturalRate != null){
                    localInfoEntity.setNaturalRate(naturalRate.getNaturalRate());
                } else {
                    localInfoEntity.setNaturalRate(0.0F);
                }
                localInfoEntity.setName(organizationEntity1.getGbName());
                // 返回一个list集合给前端做展示
                resList.add(localInfoEntity);
            }
            crowdStatusEntity.setList(resList);
        }
        // 如果是市级或者区县级用户，那么就查询当前区划下近5年数据 趋势图
        else {
            // 获取近5年人口总数
            List<AvgCostEntity> totalList = homePageDao.getTotal(baseQueryEntity);
            // 获取近5年出生人口总数
            List<AvgCostEntity> birthList = homePageDao.getBirthTotal(baseQueryEntity);
            // 获取近5年内死亡人数
            List<AvgCostEntity> dieList = homePageDao.getDieTotal(baseQueryEntity);
            // 计算5年内每年的出生率
            List<Map<String, Object>> birthRateList = new ArrayList<>();
            for(AvgCostEntity birthEntity : birthList){
                for(AvgCostEntity totalEntity : totalList){
                    if(birthEntity.getBusDate().equals(totalEntity.getBusDate())){
                        Map<String, Object> birthMap = new HashMap<>();
                        // 每一年的出生率
                        float f1 = new BigDecimal((float)birthEntity.getTotal()/totalEntity.getTotal())
                                .setScale(3, BigDecimal.ROUND_HALF_UP).floatValue();
                        birthMap.put(birthEntity.getBusDate(), f1*100);
                        birthRateList.add(birthMap);
                    }
                }
            }
            crowdStatusEntity.setBirthRateList(birthRateList);
            //计算5年内人口自然增长率
            List<Map<String, Object>> naturalRateList = new ArrayList<>();
            // sql聚合出来的数据，每个集合最多5条数据，每条代表每年
            for(AvgCostEntity birthEntity : birthList){
                for(AvgCostEntity totalEntity : totalList){
                    if(birthEntity.getBusDate().equals(totalEntity.getBusDate())){
                        for(AvgCostEntity dieEntity : dieList){
                            if(birthEntity.getBusDate().equals(dieEntity.getBusDate())){
                                Map<String, Object> naturalMap = new HashMap<>();
                                // 每一年的自然增长率
                                float f1 = new BigDecimal((birthEntity.getTotal()-dieEntity.getTotal())/totalEntity.getTotal())
                                        .setScale(3, BigDecimal.ROUND_HALF_UP).floatValue();
                                naturalMap.put(birthEntity.getBusDate(), f1*100);
                                naturalRateList.add(naturalMap);
                            }
                        }

                    }
                }
            }
            crowdStatusEntity.setNaturalRateList(naturalRateList);
        }
        return AppResponse.success("查询成功", crowdStatusEntity);
    }

    /**
     * 获取均次费用、门诊抗菌药使用率、药占比
     * @param baseQueryEntity 参数
     * @return 结果
     */
    public AppResponse getTrendInfo(BaseQueryEntity baseQueryEntity){
        // 获取数据
        List<AvgCostEntity> yearCostList = homePageDao.getCostNum(baseQueryEntity);
        // 获取近12个月的均次数据总数
        List<AvgCostEntity> yearPerList = homePageDao.getPersonNum(baseQueryEntity);
        // 近12个月的每月均次费用
        List<AvgCostEntity> currentYearCostResult = new ArrayList<>();
        // 同期12个月的每月均次费用
        List<AvgCostEntity> lastYearCostResult = new ArrayList<>();
        // 设置近12个月和同期12个月的数据
        setTotal(yearCostList, yearPerList, currentYearCostResult, lastYearCostResult);
        Map<String, Object> result = new HashMap<>(2);
        // 获取均次费用平均数
        Float costTotal = 0.0F;
        int temp = 0;
        for(AvgCostEntity avgCostEntity : currentYearCostResult){
            costTotal += avgCostEntity.getTotal();
            temp++;
        }
        result.put("currentYearCostResult", currentYearCostResult);
        result.put("lastYearCostResult", lastYearCostResult);
        result.put("costTotal", currentYearCostResult.size() == 0?0:costTotal/temp);

        // 获取门诊抗菌药使用率
        List<AvgCostEntity> utilizationRateList = homePageDao.getUtilizationRate(baseQueryEntity);
        // 近12个月的抗菌药使用率
        List<AvgCostEntity> currentYearRateResult = new ArrayList<>();
        // 同期12个月的抗菌药使用率
        Float rateTotal = 0.0F;
        int ratetemp = 0;
        for(AvgCostEntity avgCostEntity : currentYearRateResult){
            rateTotal += avgCostEntity.getTotal();
            ratetemp++;
        }
        List<AvgCostEntity> lastYearRateResult = new ArrayList<>();
        result.put("rateTotal", currentYearRateResult.size() == 0?0:rateTotal/ratetemp);
        setRate(currentYearRateResult, lastYearRateResult, utilizationRateList);
        result.put("currentYearRateResult", currentYearRateResult);
        result.put("lastYearRateResult", lastYearRateResult);

        // 获取药占比
        List<AvgCostEntity> drugsRateList = homePageDao.getDrugsRate(baseQueryEntity);
        // 近12个月的药占比
        List<AvgCostEntity> currentYearDrugsResult = new ArrayList<>();
        // 同期12个月的药占比
        List<AvgCostEntity> lastYearDrugsResult = new ArrayList<>();
        setRate(currentYearDrugsResult, lastYearDrugsResult, drugsRateList);
        Float drugsTotal = 0.0F;
        int drugsTemp = 0;
        for(AvgCostEntity avgCostEntity : currentYearDrugsResult){
            drugsTotal += avgCostEntity.getTotal();
            drugsTemp++;
        }
        result.put("currentYearDrugsResult", currentYearDrugsResult);
        result.put("lastYearDrugsResult", lastYearDrugsResult);
        result.put("drugsTotal", currentYearDrugsResult.size() == 0?0:drugsTotal/drugsTemp);
        return AppResponse.success("查询成功", result);
    }

    /**
     * 获取床位使用率，重症床位使用率，手术例数，死亡人数
     * @param baseQueryEntity 参数
     * @return 结果
     */
    public AppResponse getHospitalTrendInfo(BaseQueryEntity baseQueryEntity){
        //
        baseQueryEntity.replaceKey("t.bus_date", "a.RCD_DT");
        baseQueryEntity.setStandbyStr(baseQueryEntity.getConditionStr().replaceAll("and t.GBCODE", "t.GBCODE"));
        baseQueryEntity.setStandbyStr(baseQueryEntity.getStandbyStr().substring(0,baseQueryEntity.getStandbyStr().indexOf("t.GBCODE")));
        List<AvgCostEntity> bedTte=  homePageDao.getBedRate(baseQueryEntity);
        Map<String, Object> result = new HashMap<>(2);
        // 获取床位使用率
        List<AvgCostEntity> utilizationRateList = homePageDao.getBedTqRate(baseQueryEntity);
        // 近12个月的床位使用率
        List<AvgCostEntity> currentYearRateResult = new ArrayList<>();
        // 同期12个月的床位使用率
        Float rateTotal = 0.0F;
        int ratetemp = 0;
        for(AvgCostEntity avgCostEntity : currentYearRateResult){
            rateTotal += avgCostEntity.getTotal();
            ratetemp++;
        }
        List<AvgCostEntity> lastYearRateResult = new ArrayList<>();
        result.put("rateTotal", bedTte.get(0).getTotal());
        setRate(currentYearRateResult, lastYearRateResult, utilizationRateList);
        result.put("currentYearRateResult", currentYearRateResult);
        result.put("lastYearRateResult", lastYearRateResult);
        // 重症床位使用率
        baseQueryEntity.setStandbyStr(baseQueryEntity.getConditionStr().replaceAll("and t.GBCODE", "t.GBCODE"));
         baseQueryEntity.setStandbyStr(baseQueryEntity.getStandbyStr().substring(0,baseQueryEntity.getStandbyStr().indexOf("t.GBCODE")));
        baseQueryEntity.setStandbyStr(baseQueryEntity.getStandbyStr().replaceAll("a.RCD_DT", "a.STAT_DATE"));
        List<AvgCostEntity> severeCase=  homePageDao.getSevereCaseRate(baseQueryEntity);
        // 获取重症床位使用率
        List<AvgCostEntity> drugsRateList = homePageDao.getSevereCaseTqRate(baseQueryEntity);
        // 近12个月的重症床位使用率
        List<AvgCostEntity> currentYearDrugsResult = new ArrayList<>();
        // 同期12个月的重症床位使用率
        List<AvgCostEntity> lastYearDrugsResult = new ArrayList<>();
        setRate(currentYearDrugsResult, lastYearDrugsResult, drugsRateList);
        Float drugsTotal = 0.0F;
        int drugsTemp = 0;
        for(AvgCostEntity avgCostEntity : currentYearDrugsResult){
            drugsTotal += avgCostEntity.getTotal();
            drugsTemp++;
        }
        result.put("currentYearDrugsResult", currentYearDrugsResult);
        result.put("lastYearDrugsResult", lastYearDrugsResult);
        result.put("drugsTotal", severeCase.get(0).getTotal());
        // 获取门诊手术人次

        baseQueryEntity.setStandbyStr(baseQueryEntity.getStandbyStr().replaceAll("a.STAT_DATE", "a.BUS_DATE"));
        List<AvgCostEntity> surgeryCase=  homePageDao.getSurgeryRate(baseQueryEntity);
       // 获取住院手术人次
        List<AvgCostEntity> surgeryZyCase=  homePageDao.getSurgeryZYRate(baseQueryEntity);

        //获取手术人次
        List<AvgCostEntity> yearPerList = homePageDao.getPersonNum(baseQueryEntity);
        // 近12个月的手术人次
        List<AvgCostEntity> currentYearCostResult = new ArrayList<>();
        // 同期12个月的手术人次
        List<AvgCostEntity> lastYearCostResult = new ArrayList<>();
        setRate(currentYearCostResult, lastYearCostResult, yearPerList);
        result.put("currentYearCostResult", currentYearCostResult);
        result.put("lastYearCostResult", lastYearCostResult);
        result.put("perTotal", surgeryCase.get(0).getTotal()+surgeryZyCase.get(0).getTotal());

        // 获取死亡人数
        List<AvgCostEntity> death=  homePageDao.getdeathRate(baseQueryEntity);

        //获取死亡人数
        List<AvgCostEntity> yeardeathList = homePageDao.getPersonNum(baseQueryEntity);
        // 近12个月的死亡人数
        List<AvgCostEntity> currentYeardeathResult = new ArrayList<>();
        // 同期12个月的死亡人数
        List<AvgCostEntity> lastYeardeathResult = new ArrayList<>();
        setRate(currentYeardeathResult, lastYeardeathResult, yeardeathList);
        result.put("currentYeardeathResult", currentYeardeathResult);
        result.put("lastYeardeathResult", lastYeardeathResult);
        result.put("deathTotal", death.get(0).getTotal());



        return AppResponse.success("查询成功", result);
    }
    /**
     * 获取公共服务
     * @param baseQueryEntity 参数
     * @return 结果
     */
    public AppResponse getPublicService(BaseQueryEntity baseQueryEntity){
        List<PublicServiceEntity> serviceEntityList = homePageDao.getPublicService(baseQueryEntity);
        // 家医签约数
        Integer GW_TYPE17Num = 0;
        // 辖区常住人口数
        Integer ZB_TYPE2Num = 0;
        // 已管理的高血压人数
        Integer GW_TYPE6Num = 0;
        // 辖区内高血压患者数
        Integer GW_TYPE5Num = 0;
        // 地区产妇建卡人数
        Integer FY_TYPE2Num = 0;
        // 产妇数
        Integer FY_TYPE3Num = 0;
        // 老年人建档数
        Integer GW_TYPE2Num = 0;
        // 老年人口数
        Integer ZB_TYPE3Num = 0;
        // 已管理的糖尿病人数
        Integer GW_TYPE10Num = 0;
        // 糖尿病患者数
        Integer GW_TYPE9Num = 0;
        // 儿童健康管理数
        Integer FY_TYPE12Num = 0;
        // 儿童人口数
        Integer ZB_TYPE5Num = 0;
        // 计算各个公共服务
        for(PublicServiceEntity publicServiceEntity : serviceEntityList){
            // 家医签约
            if("GW_TYPE17".equals(publicServiceEntity.getTargetType())){
                GW_TYPE17Num = publicServiceEntity.getTotal();
            }
            if("ZB_TYPE2".equals(publicServiceEntity.getTargetType())){
                ZB_TYPE2Num = publicServiceEntity.getTotal();
            }
            // 高血压管理
            if("GW_TYPE6".equals(publicServiceEntity.getTargetType())){
                GW_TYPE6Num = publicServiceEntity.getTotal();
            }
            if("GW_TYPE5".equals(publicServiceEntity.getTargetType())){
                GW_TYPE5Num = publicServiceEntity.getTotal();
            }
            // 孕产妇建卡
            if("FY_TYPE2".equals(publicServiceEntity.getTargetType())){
                FY_TYPE2Num = publicServiceEntity.getTotal();
            }
            if("FY_TYPE3".equals(publicServiceEntity.getTargetType())){
                FY_TYPE3Num = publicServiceEntity.getTotal();
            }
            // 老年人管理
            if("GW_TYPE2".equals(publicServiceEntity.getTargetType())){
                GW_TYPE2Num = publicServiceEntity.getTotal();
            }
            if("ZB_TYPE3".equals(publicServiceEntity.getTargetType())){
                ZB_TYPE3Num = publicServiceEntity.getTotal();
            }
            // 糖尿病管理
            if("GW_TYPE10".equals(publicServiceEntity.getTargetType())){
                GW_TYPE10Num = publicServiceEntity.getTotal();
            }
            if("GW_TYPE9".equals(publicServiceEntity.getTargetType())){
                GW_TYPE9Num = publicServiceEntity.getTotal();
            }
            // 儿童健康管理
            if("FY_TYPE12".equals(publicServiceEntity.getTargetType())){
                FY_TYPE12Num = publicServiceEntity.getTotal();
            }
            if("ZB_TYPE5".equals(publicServiceEntity.getTargetType())){
                ZB_TYPE5Num = publicServiceEntity.getTotal();
            }
        }
        Map<String, Object> result = new HashMap<>();
        setMap(result, GW_TYPE17Num, ZB_TYPE2Num, "type1");
        setMap(result, GW_TYPE6Num, GW_TYPE5Num, "type2");
        setMap(result, FY_TYPE2Num, FY_TYPE3Num, "type3");
        setMap(result, GW_TYPE2Num, ZB_TYPE3Num, "type4");
        setMap(result, GW_TYPE10Num, GW_TYPE9Num, "type5");
        setMap(result, FY_TYPE12Num, ZB_TYPE5Num, "type6");
        return AppResponse.success("查询成功", result);
    }

    /**
     * 获取中医服务
     * @param baseQueryEntity 参数
     * @return 结果
     */
    public AppResponse getChMedicine(BaseQueryEntity baseQueryEntity){
        Map<String, Object> result = new HashMap<>();
        result.put("personRate", homePageDao.getChMedicine(baseQueryEntity));
        result.put("drugsRate", homePageDao.getChMedicineRate(baseQueryEntity));
        return AppResponse.success("查询成功", result);
    }

    /**
     * 获取昨日发热人次、肠道门诊人次
     * @param baseQueryEntity 参数
     * @return 结果
     */
    public AppResponse getLastDayDis(BaseQueryEntity baseQueryEntity){
        Map<String, Object> result = new HashMap<>();
        result.put("lastDayInfo", homePageDao.getLastDayDis(baseQueryEntity));
        // 获得近7日数据
        List<HotEntity> currentList = homePageDao.getHotNum(baseQueryEntity);
        // 获得同期近7日数据
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(baseQueryEntity.getKeyDate());
        //当前时间减去一年，即一年前的时间
        calendar.add(Calendar.YEAR, -1);
        baseQueryEntity.setKeyDate(calendar.getTime());
        List<HotEntity> lastYearList = homePageDao.getHotNum(baseQueryEntity);
        result.put("currentList", currentList);
        result.put("lastYearList", lastYearList);
        return AppResponse.success("查询成功", result);
    }

    /**
     * 获取千人口医师，护士，床位
     * @param baseQueryEntity 参数
     * @return 结果
     */
    public AppResponse getHealthRes(BaseQueryEntity baseQueryEntity){
        HealthResEntity healthResEntity = homePageDao.getHealthRes(baseQueryEntity);
        float f1 = 0;
        float f2 = 0;
        float f3 =0;
        if(healthResEntity.getCapitaTotal()==null || healthResEntity.getCapitaTotal()==0){
            f1=0;
            f2=0;
            f3=0;
        }else{
             f1 = new BigDecimal((float)healthResEntity.getDoctorNum()/healthResEntity.getCapitaTotal()).setScale(3, BigDecimal.ROUND_HALF_UP).floatValue();
             f2 = new BigDecimal((float)healthResEntity.getNurseNum()/healthResEntity.getCapitaTotal()).setScale(3, BigDecimal.ROUND_HALF_UP).floatValue();
             f3 = new BigDecimal((float)healthResEntity.getBedTotal()/healthResEntity.getCapitaTotal()).setScale(3, BigDecimal.ROUND_HALF_UP).floatValue();
        }
        healthResEntity.setDoctorRate(f1*100);
        healthResEntity.setNurseRate(f2*100);
        healthResEntity.setBedRate(f3*100);
        return AppResponse.success("查询成功", healthResEntity);
    }

    /**
     * 获取医疗服务
     * @param baseQueryEntity 参数
     * @return 结果
     */
    public AppResponse getMedical(BaseQueryEntity baseQueryEntity){
        List<MedicalEntity> mzList = homePageDao.getMZMedical(baseQueryEntity);
        List<MedicalEntity> zyList = homePageDao.getZYMedical(baseQueryEntity);
        Map<String, Object> result = new HashMap<>();
        result.put("mz", mzList);
        result.put("zy", zyList);
        return AppResponse.success("查询成功", result);
    }

    /**
     * 获取昨日省内门诊就诊流向
     * @param baseQueryEntity 参数
     * @return 结果
     */
    public AppResponse getOutpatientFlow(BaseQueryEntity baseQueryEntity){
        int aType = ThreadLocalUtil.get().getBody().getAreainfo().getAtype();
        if(aType == 2){
            baseQueryEntity.setSubstrIndex(4);
        } else if(aType == 3){
            baseQueryEntity.setSubstrIndex(6);
        } else if(aType == 4){
            baseQueryEntity.setSubstrIndex(8);
        }
        return AppResponse.success("查询成功", homePageDao.getOutpatientFlow(baseQueryEntity));
    }

    /**
     * 获取半年内住院就诊流向
     * @param baseQueryEntity 参数
     * @return 结果
     */
    public AppResponse getInHospitalFlow(BaseQueryEntity baseQueryEntity){
        int aType = ThreadLocalUtil.get().getBody().getAreainfo().getAtype();
        if(aType == 2){
            baseQueryEntity.setSubstrIndex(4);
        } else if(aType == 3){
            baseQueryEntity.setSubstrIndex(6);
        } else if(aType == 4){
            baseQueryEntity.setSubstrIndex(8);
        }
        return AppResponse.success("查询成功", homePageDao.getInHospitalFlow(baseQueryEntity));
    }

    /**
     * 获取外来就诊流向
     * @param baseQueryEntity 参数
     * @return 结果
     */
    public AppResponse getForeignFlow(BaseQueryEntity baseQueryEntity){
        // 说明 原型图中前两个柱状图，直接使用昨日省内门诊就诊流向，从哪里到哪里，多少个数据，
        // 如果前端不做，把昨日省内门诊就诊流向传回来，后端直接计算数据，比查询库快目前
        // 后端目前只查询兵种排名
        Map<String, Object> result = new HashMap<>();
        int aType = ThreadLocalUtil.get().getBody().getAreainfo().getAtype();
        if(aType == 2){
            baseQueryEntity.setSubstrIndex(4);
        } else if(aType == 3){
            baseQueryEntity.setSubstrIndex(6);
        } else if(aType == 4){
            baseQueryEntity.setSubstrIndex(8);
        }
        baseQueryEntity.replaceKey("bus_date","see_doc_dt");
        baseQueryEntity.replaceKey("GBCODE","organ_code");
        //查询门诊就诊流向排名
        List<OutpatientFlowEntity> jzlx = homePageDao.getJzlxFlow(baseQueryEntity);
        result.put("jzlx",jzlx);
        //查询病种排名
        List<OutpatientFlowEntity> bzpm = homePageDao.getBzFlow(baseQueryEntity);
        result.put("bzpm",bzpm);
        return AppResponse.success("查询成功", result);
    }

    /**
     * 设置返回结果集
     * @param result
     * @param num
     * @param total
     * @param key
     */
    private void setMap(Map<String, Object> result, int num, int total, String key){
        PublicServiceEntity publicServiceEntity = new PublicServiceEntity();
        publicServiceEntity.setTotal(num);
        float f1=0;
        if(total!=0) {
             f1 = new BigDecimal((float) num / total).setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
        }
        publicServiceEntity.setRate(f1*100);
        result.put(key, publicServiceEntity);
    }

    /**
     * 计算门诊抗菌药使用率
     */
    private void setRate(List<AvgCostEntity> currentYearRateResult, List<AvgCostEntity> lastYearRateResult, List<AvgCostEntity> utilizationRateList){
        boolean addFlag = true;
        for(AvgCostEntity avgCostEntity : utilizationRateList){
            if(addFlag){
                currentYearRateResult.add(avgCostEntity);
                if(avgCostEntity.getBusDate().equals(avgCostEntity.getKeyMonth())){
                    addFlag = false;
                }
            } else {
                lastYearRateResult.add(avgCostEntity);
            }
        }
    }

    /**
     * 计算均次费用
     * @param yearCostList
     * @param yearPerList
     * @param currentYearResult
     * @param lastYearResult
     */
    private void setTotal(List<AvgCostEntity> yearCostList, List<AvgCostEntity> yearPerList, List<AvgCostEntity> currentYearResult, List<AvgCostEntity> lastYearResult){
        boolean addFlag = true;
        for(AvgCostEntity costEntity: yearCostList){
            for(AvgCostEntity perEntity : yearPerList){
                // 同一个月分的数据
                if(costEntity.getBusDate().equals(perEntity.getBusDate())){
                    // 费用/人次 = 均次费用
                    Float money = costEntity.getTotal()/perEntity.getTotal();
                    AvgCostEntity resultEntity = new AvgCostEntity();
                    resultEntity.setBusDate(costEntity.getBusDate());
                    resultEntity.setTotal(money);
                    // 比较月份，判断是近12个月数据还是同期数据
                    if(addFlag){
                        currentYearResult.add(resultEntity);
                        if(costEntity.getBusDate().equals(costEntity.getKeyMonth())){
                            addFlag = false;
                        }
                    } else {
                        lastYearResult.add(resultEntity);
                    }
                }
            }
        }
    }

    private static String setStr(String str){
        int startIndex =  str.indexOf("and t.GBCODE");
        int endIndex = str.indexOf("%'")+2;

        String result = "";
        if(startIndex != 0){
            result = str.substring(0, startIndex);
        }
        result += str.substring(endIndex);
        return result;
    }
}
